package com.luojiaoj

import grails.plugins.springsecurity.Secured
import org.springframework.web.multipart.MultipartHttpServletRequest
import org.springframework.web.multipart.commons.CommonsMultipartFile
import grails.converters.JSON
import org.springframework.web.multipart.MultipartFile
import javax.servlet.http.HttpServletResponse

class ProfileController {

    def grailsApplication
    def springSecurityService
    def uploadService

    @Secured(["ROLE_ADMIN", "ROLE_USER"])
    def profile() {
        User currentUser = springSecurityService.currentUser
        def userInstance = User.get(currentUser.id)
        if (!userInstance) {
            redirect(controller: 'login', action: 'auth')
            return
        }

        [userInstance: userInstance]
    }

    @Secured(["ROLE_ADMIN", "ROLE_USER"])
    def setting(long id) {
        def fromUser = User.get(id)
        def userInstance = springSecurityService.currentUser
        if (fromUser != userInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'ljoj.onlinejudge.user.label', default: 'User'), params.id])
            redirect(controller: 'logout')
            return
        }

        render(template: 'setting', model: [userInstance: userInstance])
    }

    @Secured(["ROLE_ADMIN", "ROLE_USER"])
    def avatar(long id) {
        def fromUser = User.get(id)
        def userInstance = springSecurityService.currentUser
        if (fromUser != userInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'ljoj.onlinejudge.user.label', default: 'User'), params.id])
            redirect(controller: 'logout')
            return
        }

        render(template: 'avatar', model: [userResult: [name: fromUser.username, id: fromUser.id, avatarName: fromUser.avatar?.getPhotoFileName()]])
    }

    @Secured(["ROLE_ADMIN", "ROLE_USER"])
    def info() {
        User currentUser = springSecurityService.currentUser
        def userInstance = User.get(currentUser.id)
        if (!userInstance) {
            redirect(controller: 'login', action: 'auth')
            return
        }

        render(template: 'info', model: [userInstance: userInstance])
    }

    @Secured(["ROLE_ADMIN", "ROLE_USER"])
    def saveAsUserAvator() {
        User currentUser = springSecurityService.currentUser
        def userInstance = User.get(currentUser.id)
        if (!userInstance) {
            redirect(controller: 'login', action: 'auth')
            return
        }

        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request
            CommonsMultipartFile orginalFile = (CommonsMultipartFile) multiRequest.getFile("qqfile")
            MultipartFile multipartFile = null
            // 判断是否上传文件
            if (orginalFile != null && !orginalFile.isEmpty()) {
                try{
                    multipartFile = selectMultipartFile('qqfile')

                }catch (Exception e){
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST)
                    return
                }

                if (!multipartFile){
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST)
                    return
                }

                uploadService.saveAsUserAvatar(multipartFile.inputStream, multipartFile.originalFilename, currentUser.id)

                render([success: true] as JSON)
                return
            }

        } else {
            println "No multipart"
        }
    }

    @Secured(["ROLE_ADMIN", "ROLE_USER"])
    def uploadPhoto() {
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request
            CommonsMultipartFile orginalFile = (CommonsMultipartFile) multiRequest.getFile("qqfile")
            MultipartFile multipartFile = null
            // 判断是否上传文件
            if (orginalFile != null && !orginalFile.isEmpty()) {
                // 获取系统默认文件路径分隔符
                def separator = System.getProperty("file.separator")
                println "file separator is ${separator} "
                // 获取原文件名称
                String originalFilename = orginalFile.getOriginalFilename()

                try{
                    multipartFile = selectMultipartFile('qqfile')

                }catch (Exception e){
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST)
                    return
                }

                if (!multipartFile){
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST)
                    return
                }
                // 使用存放文件的绝对路径创建输出流
                /**
                 DataOutputStream out = new DataOutputStream(new FileOutputStream(name))
                 InputStream is = null
                 try {
                 is = orginalFile.getInputStream()
                 byte[] buffer = new byte[1024]
                 while (is.read(buffer) > 0) {
                 out.write(buffer) // 写入磁盘
                 }
                 } catch (IOException exception) {
                 exception.printStackTrace()
                 } finally {
                 if (is != null) {
                 is.close()
                 }
                 if (out != null) {
                 out.close()
                 }
                 }
                 */

                uploadService.savePhoto(multipartFile.inputStream, multipartFile.originalFilename)
//                File uploadDir = new File(grailsApplication.config.ljoj.upload.dir)
//                File imageFolder = new File(uploadDir, 'image')
//                if (!imageFolder.exists()){
//                    imageFolder.mkdirs()
//                }
//                File imageFile = new File(imageFolder, System.currentTimeMillis() + ".jpg")
//                try {
//                    orginalFile.transferTo(imageFile)
//                } catch (Exception e) {
//                    e.printStackTrace()
//                }
                render([success: true] as JSON)
                return
            }

        } else {
            println "No multipart"
        }
    }

    private MultipartFile selectMultipartFile(String paramName){
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request
            MultipartFile uploadedFile = multipartRequest.getFile(paramName)
            return uploadedFile
        } else if (params[paramName] instanceof MultipartFile){
            return (MultipartFile)params[paramName]
        }
        return null
    }
}
